package com.atguigu.day01;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class Example3 {
    public static void main(String[] args) throws Exception {
        // 队列容量为10
        var queue = new ArrayBlockingQueue<Integer>(10);

        var producer = new Producer(queue);
        var consumer = new Consumer(queue);

        var t1 = new Thread(producer);
        var t2 = new Thread(consumer);

        t1.start();
        t2.start();

        // 等两个程序执行完毕再退出
        t1.join();
        t2.join();
    }

    public static class Producer implements Runnable {
        // 阻塞队列
        private final BlockingQueue<Integer> queue;

        public Producer(BlockingQueue<Integer> queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                queue.add(i);
                try {
                    Thread.sleep(1000L);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    public static class Consumer implements Runnable {
        private final BlockingQueue<Integer> queue;

        public Consumer(BlockingQueue<Integer> queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
            while (true) {
                var value = queue.poll();
                if (value == null) continue;
                else System.out.println(value * value);
            }
        }
    }
}
